package rpc

import (
	"bigdevops/src/cache"
	"bigdevops/src/config"
	"bigdevops/src/pbms"
	"github.com/shimingyah/pool"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
	"net"
)

func StartServerGrpc(sc *config.ServerConfig, taskCache *cache.TaskCache) error {

	lis, err := net.Listen("tcp", sc.GrpcServerConfigC.Addr)
	if err != nil {
		sc.Logger.Fatal("grpc端口监听失败", zap.Error(err))
	}
	// 创建一个grpc Server服务对象,Handler非必传
	// s := grpc.NewServer() // 可以直接创建对象

	infoReporterServer := &InfoReportServer{sc: sc}
	jobExecServer := &JobExecServer{
		sc:        sc,
		taskCache: taskCache,
	}

	//s := grpc.NewServer()

	s := grpc.NewServer(
		grpc.InitialWindowSize(pool.InitialWindowSize),
		grpc.InitialConnWindowSize(pool.InitialConnWindowSize),
		grpc.MaxSendMsgSize(pool.MaxSendMsgSize),
		grpc.MaxRecvMsgSize(pool.MaxRecvMsgSize),
		grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
			PermitWithoutStream: true,
		}),
		grpc.KeepaliveParams(keepalive.ServerParameters{
			Time:    pool.KeepAliveTime,
			Timeout: pool.KeepAliveTimeout,
		}),
	)
	// 注册服务
	pbms.RegisterInfoReporterServer(s, infoReporterServer)
	pbms.RegisterJobExecServer(s, jobExecServer)

	// 启动RPC并监听
	sc.Logger.Info("grpc-server启动", zap.Any("监听地址", lis.Addr()))
	err = s.Serve(lis)
	if err != nil {
		sc.Logger.Info("grpc-server启动失败", zap.Any("监听地址", lis.Addr()),
			zap.Error(err),
		)
	}
	return err

}
